import React from 'react';
import {Icon, Input, Button, Checkbox, message} from 'antd';
import Form from './index';

/**
 * 表单的demo
 */
class Test extends React.Component {
  constructor(props) {
    super(props);
    //表单项属性
    this.formItemProps = {
      label: ' ',
      labelCol: {span: 6},
      wrapperCol: {span: 12}
    };
  }

  render() {
    let prefix = <Icon type="user" style={{color: 'rgba(0,0,0,.25)'}} />;
    return (
      <Form
        labelAlign="right" //标签对齐方式
        layout="horizontal" //表单布局
        labelCol={{span: 6, offset: 0}} //标签的栅格占比
        wrapperCol={{span: 12, offset: 0}} //文本的栅格占比
        onSubmit={this.handleSubmit}
      >
        <Form.Item
          label="用户名"
          formId="user"
          formConfig={{
            initialValue: 'user', //初始值
            valuePropName: 'value', //用来指定组件的属性名，默认为value
            rules: [{required: true, message: '请输入用户名!'}]
          }}
          formChild={<Input prefix={prefix} placeholder="请输入用户名" onChange={this.onChangeUser} />}
        />
        <Form.Item
          label="密码"
          formId="password"
          formConfig={{
            rules: [{required: true, message: '请输入密码!'}]
          }}
          formChild={
            <Input
              prefix={<Icon type="lock" style={{color: 'rgba(0,0,0,.25)'}} />}
              type="password"
              placeholder="请输入密码"
            />
          }
        />
        <Form.Item
          {...this.formItemProps}
          formId="check"
          formConfig={{valuePropName: 'checked'}}
          formChild={<Checkbox>Remember me</Checkbox>}
        >
          <Button type="primary" htmlType="submit">
            Log in
          </Button>
        </Form.Item>
      </Form>
    );
  }

  /**
   * 修改用户名的回调
   */
  onChangeUser = (e) => {
    let value = e.target.value;
    if (value) e.target.value = value.toUpperCase(); //自动转大写
  };

  /**
   * 提交表单
   */
  handleSubmit = (e) => {
    e.preventDefault();
    //校验表单，并滚动到错误位置
    this.props.form.validateFieldsAndScroll((err, values) => {
      console.log(values);
      if (!err) {
        message.success('登录成功');
      }
    });
  };
}

/**
 * 使用Form.create()，从而在组件中使用this.props.form进行表单操作
 */
export default Form.create({})(Test);
